import React, {MutableRefObject, useEffect, useRef, useState} from 'react';
import { Image, Layout } from 'antd';
import * as API from '@/services';
import defaultPlaceholderPng from '@/assets/placeholder.png';
import videoPng from '@/assets/video.png';
import MaterialGroupTree, { MaterialGroupTreeAction } from '@/pages/biz/Material/components/MaterialGroupTree';
import './index.less';
import QuickForm from '@/pages/biz/Material/components/QuickForm';
import { KfTablePickerAction, KfTablePickerProps, KfTableSelect, useBackendEnum } from 'kf-web-library';
import {MaterialType} from "@/components";

type Entity = API.Material;
type EntityPageQueryParams = API.MaterialPageQueryParams;

export interface KfMaterialPickerProps
  extends Omit<KfTablePickerProps<Entity, EntityPageQueryParams>, 'entityTypeName' | 'entityKeys' | 'columns' | 'pagingQuery' | 'primaryKeysQuery'> {
  type: MaterialType
}

const KfMaterialPicker: React.FC<KfMaterialPickerProps> = (props) => {
  const { multiple = false, type, actionRef: compActionRef, ...rest } = props;

  const [groupId, setGroupId] = useState<API.EntityId | undefined>(undefined);

  const { enumDict } = useBackendEnum();
  const typeName = enumDict['MaterialType'][type].enumDesc;

  const tsActionRef = useRef<KfTablePickerAction<Entity, EntityPageQueryParams>>();
  const tableActionRef: React.RefObject<KfTablePickerAction<Entity, EntityPageQueryParams> | undefined> = compActionRef || tsActionRef;

  const treeActionRef = useRef<MaterialGroupTreeAction>();
  useEffect(() => {
    tableActionRef.current?.pagingTableRef?.current?.reload();
  }, [groupId]);

  return (
    <KfTableSelect<Entity, EntityPageQueryParams>
      actionRef={tableActionRef}
      entityTypeName={'素材'}
      entityKeys={{
        primaryKey: 'id',
        labelKey: (d) => `${d.name}`,
      }}
      modelWidth={1200}
      multiple={multiple}
      pagingQuery={(params) => {
        return API.queryMaterials({ ...params, types: [type], groupId });
      }}
      primaryKeysQuery={(primaryKeys) => {
        const emptyResult = { flag: true, data: [] } as API.RespListResult<Entity>;
        return new Promise<API.RespListResult<Entity>>((resolve) => resolve(emptyResult));
      }}
      pagingTable={{
        headerTitle: null,
        proTable: {
          search: {
            filterType: 'query',
          },
        },
        opFloatingsDef: {
          noargs: {
            "createModal": {
              show: true,
              buttonText: '上传',
              fltRender: () => {
                return {
                  title: `上传${typeName}`,
                  content: <QuickForm formType={'create'} type={type} defaultGroupId={groupId} />,
                  fltType: 'modal',
                  fltModal: {
                    width: 800,
                  },
                };
              },
            },
          },
        },
        onFloatingSubmit: (fltTypeName)=>{
          if ([ "createModal", "moveModal"].includes(fltTypeName)) {
            treeActionRef.current?.reload();
          }
        }
      }}
      renderPicker={(pickerPagingTable, pickerSelectedList, selectedRowKeys, selectedRows) => {
        return (
          <div>
            <Layout className={'kf-material-picker material-group-page-layout'}>
              <Layout.Sider theme={'light'} collapsible={false} width={280} className={'material-group-tree-sider'}>
                <MaterialGroupTree
                  actionRef={treeActionRef}
                  selectedKey={groupId}
                  type={type}
                  onSelect={(selectedKeys) => {
                    setGroupId(selectedKeys);
                  }}
                  readonly={true}
                />
              </Layout.Sider>
              <Layout.Content>{pickerPagingTable}</Layout.Content>
              <Layout.Sider theme="light" width={170}>
                {pickerSelectedList}
              </Layout.Sider>
            </Layout>
          </div>
        );
      }}
      columns={[
        {
          title: ``,
          width: 60,
          dataIndex: nameof<Entity>((x) => x.url),
          sorter: false,
          hideInSearch: true,
          ellipsis: true,
          render: (_, record) => {
            if (type === 'IMG') {
              return <Image width={32} src={record.url} fallback={defaultPlaceholderPng} />;
            } else {
              return (
                <a rel={'noreferrer'} href={record.url} target={'_blank'}>
                  <img src={videoPng} style={{ width: 32 }} />
                </a>
              );
            }
          },
        },
        {
          title: `${typeName}名称`,
          dataIndex: nameof<Entity>((x) => x.name),
          sorter: false,
          hideInSearch: false,
          ellipsis: false,
        },

        {
          title: '上传时间',
          width: 150,
          dataIndex: nameof<Entity>((x) => x.createTime),
          sorter: false,
          hideInSearch: true,
          ellipsis: true,
        },
      ]}
      {...rest}
    />
  );
};

export default KfMaterialPicker;
